package cn.hairui.blog.controller.manage;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Album;
import cn.hairui.blog.model.User;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.service.AlbumService;
import cn.hairui.blog.service.WebInfoService;
import cn.hairui.blog.util.CommUtil;
import cn.hairui.blog.util.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * <h2>请添加说明
 * </h2>
 * <ol>请添加详细说明
 * </ol>
 *
 * <h2>修改历史
 * </h2>
 * <ol>如有修改，请添加修改历史
 * </ol>
 *
 * </p>
 *
 * @author laoganbu
 * @version V1.0
 * @date 2019/8/9 16:36
 */
@Controller
@RequestMapping(value = "/manage")
public class AlbumManageController {

    @Autowired
    private AlbumService albumService;
    @Autowired
    private WebInfoService webInfoService;

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //列表页面
    @RequestMapping(value = "page/album/albumList")
    public String albumList() {
        return "manage/page/album/albumList";
    }

    //新增页面
    @RequestMapping(value = "page/album/albumAdd")
    public String albumAdd() {
        return "manage/page/album/albumAdd";
    }

    //修改页面
    @RequestMapping(value = "page/album/albumUpdate")
    public String albumUpdate(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        Album album = albumService.find(id);
        model.addAttribute("album", album);
        return "manage/page/album/albumUpdate";
    }


    //内容编辑页面
    @RequestMapping(value = "page/album/albumImgEdit")
    public String albumImgEdit(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        model.addAttribute("albumId", id);
        return "manage/page/album/albumImgList";
    }


    //列表数据
    @RequestMapping(value = "page/album/albumImgData")
    @ResponseBody
    public String albumImgData(HttpServletRequest request, Model model) {
        Map map = new HashMap<Object, Object>();
       /* int pageSize = 5;//默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);*/
        int id = Integer.parseInt(request.getParameter("id"));
        List<Map> albumList = albumService.findImgsJsonByAlbuId(id);

        /*PageInfo<Map> pageInfo = new PageInfo<Map>(albumList);*/

        map.put("data", albumList);
        map.put("title", "照片管理");
        map.put("id", "Images");
        map.put("start", 0);

        return JSONUtils.toJSONString(map);
    }


    //列表数据
    @RequestMapping(value = "page/album/list")
    @ResponseBody
    public String list(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 5;//默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> albumList = albumService.listMgr();

        PageInfo<Map> pageInfo = new PageInfo<Map>(albumList);
        map.put("data", albumList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }

    //公开展示
    @RequestMapping(value = "page/album/albumshow")
    @ResponseBody
    public String albumshow(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int id = Integer.parseInt(request.getParameter("id"));

        Album album = albumService.find(id);
        String flag = "";
        if (PubConstant.YES_NO_Y.equals(album.getShowFlag())) {
            //取消置顶
            flag = PubConstant.YES_NO_N;

        } else {
            //置顶
            flag = PubConstant.YES_NO_Y;
        }
        albumService.updateIsShow(id, flag);
        map.put(PubConstant.flag, flag);
        return JSONUtils.toJSONString(map);
    }

    //新增数据
    @RequestMapping(value = "page/album/add")
    @ResponseBody
    public String add(HttpServletRequest request, Album album) {
        Map map = new HashMap<Object, Object>();
        //处理分类置顶

        if (PubConstant.SWITCH_ON.equals(album.getShowFlag())) {
            album.setShowFlag(PubConstant.YES_NO_Y);
        } else {
            album.setShowFlag(PubConstant.YES_NO_N);
        }
        //设置默认时间 添加人
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        album.setCreator(userinfo.getUsername());
        album.setCreateTime(DateUtil.getCurrentTime());


        String fileName = "";
        File targetPath = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //重新生成文件名
                    fileName = CommUtil.getUUIDUpperCase() + suffixName;

                    System.out.println(fileName);
                    String path = uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR + fileName;
                    //上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        album.setShowImg(fileName);
        albumService.add(album);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    @RequestMapping(value = "page/album/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        //判断权限
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null || !PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //普通用户或者游客 无权限删除文章
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {
            //管理员
            Album album = albumService.find(id);
            albumService.deleteById(id);
            try {
                //删除文件
                String fileName = album.getShowImg();

                File file = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR + fileName);
                if (file.exists() && fileName != null && !"".equals(fileName)) {
                    file.delete();
                }
            } catch (Exception e) {

            }
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }

    /*//更新数据
    @RequestMapping(value = "page/album/update")
    @ResponseBody
    public String update(HttpServletRequest request, Album album) {
        Map map = new HashMap<Object, Object>();
        //处理专题编号
        if (PubConstant.SWITCH_ON.equals(album.getIsShow())) {
            album.setIsShow(PubConstant.YES_NO_Y);
        }else{
            album.setIsShow(PubConstant.YES_NO_N);
            album.setShowOrder(null);
        }
        albumService.update(album);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    //删除数据




    //首页展示置顶
    @RequestMapping(value = "page/album/albumtop")
    @ResponseBody
    public String albumtop(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int id = Integer.parseInt(request.getParameter("id"));
        //TODO 置顶算法
        albumService.updateShowOrder(id, PubConstant.ONE);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }*/
}
